package cn.example.vip.mall.canal.dynamic;


import com.dangdang.ddframe.job.api.simple.SimpleJob;
import com.dangdang.ddframe.job.config.JobCoreConfiguration;
import com.dangdang.ddframe.job.config.simple.SimpleJobConfiguration;
import com.dangdang.ddframe.job.lite.config.LiteJobConfiguration;
import com.dangdang.ddframe.job.lite.spring.api.SpringJobScheduler;
import com.dangdang.ddframe.job.reg.zookeeper.ZookeeperRegistryCenter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class DynamicTaskCreate {
	
	@Autowired
	private ZookeeperRegistryCenter zookeeperRegistryCenter;
	
	/**
	 * 作业创建 LiteJobConfiguration
	 * @param jobName Task 名称
	 * @param cron cron表达式 表示执行周期
	 * @param shardingTotalCount 分片数量
	 * @param instance	Task:SimpleJob 实例
	 * @param parameters 额外参数
	 */
	public void create(String jobName,
					   String cron,
					   int shardingTotalCount,
					   SimpleJob instance,
					   String parameters) {
		// 1.配置 Task
		LiteJobConfiguration.Builder jobBuilder =
			LiteJobConfiguration.newBuilder(new SimpleJobConfiguration(
				JobCoreConfiguration.newBuilder(jobName, cron, shardingTotalCount)
					.jobParameter(parameters)
					.build(),
				instance.getClass().getName()
			)).overwrite(true);	// 覆写方法
		
		LiteJobConfiguration liteJobConfiguration = jobBuilder.build();
		
		// 2.启动 Task
		new SpringJobScheduler(instance, zookeeperRegistryCenter, liteJobConfiguration).init();
	}
}
